package com.zeta.plan.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    public static final int EXPIRE_TIME= 5*60*1000;//token到期时间5分钟，毫秒为单位
    public static final long REFRESH_EXPIRE_TIME=30*60;//RefreshToken到期时间为30分钟，秒为单位

    /**
     * 生成token
     * @param payload
     * @param secret
     * @return
     */
    public static String createToken(long createdTime ,Map<String, String> payload, String secret) {
        JWTCreator.Builder tokenBuilder = JWT.create();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("type", "JWT");
        headerMap.put("alg","HS256");
        tokenBuilder.withIssuer("auth0")
                .withHeader(headerMap);
        payload.forEach((k, v) -> tokenBuilder.withClaim(k, v));
        String token = tokenBuilder.withExpiresAt(new Date(createdTime + EXPIRE_TIME))
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 验证token
     * @param token
     * @param secret
     * @return
     */
    public static boolean verify(String token, String secret) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret))
                    .withIssuer("auth0")
                    .build();
            jwtVerifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 从token中获取用户名
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        try {
            return JWT.decode(token).getClaim("username").asString();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从token中获取创建时间
     * @param token
     * @return
     */
    public static String getCreatedTime(String token) {
        try {
            return JWT.decode(token).getClaim("createdTime").asString();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }
}